package com.CMUBiS.Depreciated;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.util.Image;
import com.CMUBiS.util.Item;

@WebServlet(name="ViewItemold", urlPatterns={"/viewitemold"})
public class ViewItem extends HttpServlet {
	private static final long serialVersionUID = 6475041003023438743L;
	private static final String EMPTY = "";
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StringBuffer errorString = new StringBuffer();
		Map<String, String[]> paramMap = request.getParameterMap();
		
		// Make sure the bid is correct
		if(!paramMap.isEmpty()){
			boolean itemExists = false;
			int itemID=-1;
			int quantity=-1;
			float bid=-1;
			float maxBid=-1;
			int userID=-1;
			String authToken=null;
			
			/*
			 * If the user only passes an item ID then they are browsing the page, not bidding
			 */
			if(paramMap.containsKey("itemID") && !paramMap.containsKey("maxBid") && !paramMap.containsKey("quantity")){
				this.makePage(request, response, "");
			}
			/*
			 * Otherwise the user has given additional parameters and is trying to bid
			 */
			else{
				
				/*
				 * Check the userID is present and correct
				 */
				if(!paramMap.containsKey("userID") || request.getParameter("userID").equals(EMPTY)){
						errorString.append("You must provide a userID. <br />");
				}
				else{
					// make sure the userID is a number
					try{
						userID = Integer.parseInt(request.getParameter("userID"));
						
						if(userID <0)
							errorString.append("The userID must be greater than zero <br />");
					}
					catch(Exception e){
						errorString.append("The userID must be a number. <br />");
					}
				}
				
				/*
				 * Check the auth token is passed
				 */
				if(!paramMap.containsKey("authToken") || request.getParameter("authToken").equals(EMPTY)){
					errorString.append("You must provide an auth token. <br />");
				}
				else
					authToken = request.getParameter("authToken");
				
				/*
				 * Check the the Item ID is valid and the auction is still going
				 */
				if(paramMap.containsKey("itemID")){
					// Make sure the itemID is not blank
					if(!request.getParameter("itemID").equals(EMPTY)){
						// Make sure the itemID is a number
						try{
							itemID = Integer.parseInt(request.getParameter("itemID"));
							
							// Make sure the auction is still going
							Date endDate = GlobalVars.db.getItemEndDate(itemID);
							Date now = new Date();
							
							if(endDate.before(now)){
								errorString.append("Sorry, bidding on that item has finished. Better luck next time. <br />");
							}
							
							// If the end time is okay now, then we will enter the users bid (if all the other info is okay)
							// Even though the end time may tick past while we're doing the next part of the processing
							// they have submitted their bid on time
							else{
								itemExists = true;
							}
						}
						catch(Exception e){
							errorString.append("The item ID you passed is not a number. <br />");
						}
					}
					else{
						errorString.append("The item ID cannot be empty. <br />");
					}
				}
				else{
					errorString.append("You cannot bid unless you tell us which item. <br />");
				}
				
				/*
				 * Check that the bid is valid. i.e. present, a number and more than the current
				 */
				if(paramMap.containsKey("bid")){
					if(!request.getParameter("bid").equals(EMPTY)){
						// Make sure the bid is a number
						try{
							bid = Float.parseFloat(request.getParameter("bid"));
							
							// Check that the bid is positive
							if(bid>0f){
								// Check that the bid is more than the current bid
								if(itemExists){
									float currentBid = GlobalVars.db.getCurrentBid(itemID);
									
									if(currentBid >= bid){
										errorString.append("Your bid must be greater than the current bid. <br />");
									}
								}
							}
							else{
								errorString.append("Nice try, I don't think the sell will pay you to take their item. <br />");
							}
							
						}
						catch(Exception e){
							errorString.append("The bid you entered is not a number. <br />");
						}
					}
					else{
						errorString.append("You must enter a value in to the bid box. <br />");
					}
				}
				else{
					errorString.append("You cannot bid for an item without posting a bid value. <br />");
				}
				
				/*
				 * Check that the max bid is valid. i.e. present, a number and more than the current bid and the users bid
				 */
				if(paramMap.containsKey("maxBid")){
					if(!request.getParameter("maxBid").equals(EMPTY)){
						// Make sure the bid is a number
						try{
							maxBid = Float.parseFloat(request.getParameter("maxBid"));
							
							// Check that the max bid is positive
							if(maxBid>0f){
								// Check that the max bid is more than the current max bid
								if(itemExists){
									float currentBid = GlobalVars.db.getCurrentBid(itemID);
									
									if(currentBid >= maxBid){
										errorString.append("Your max bid must be greater than the current bid. <br />");
									}
									if(bid > maxBid){
										errorString.append("Your max bid must be greater than your bid. <br />");
									}
								}
							}
							else{
								errorString.append("Nice try, I don't think the sell will pay you to take their item. <br />");
							}
							
						}
						catch(Exception e){
							errorString.append("The max bid you entered is not a number. <br />");
						}
					}
					else{
						errorString.append("You must enter a value in to the max bid box. <br />");
					}
				}
				else{
					errorString.append("You cannot bid for an item without posting a max bid value. <br />");
				}
				
				/*
				 * Check that the quantity of items is valid
				 */
				if(paramMap.containsKey("quantity")){
					if(!request.getParameter("quantity").equals(EMPTY)){
						// Make sure the quantity is a number
						try{
							quantity = Integer.parseInt(request.getParameter("quantity"));
							
							// Check that the quantity is positive
							if(quantity>0){
								// Check that the bid is more than the current max bid
								if(itemExists){
									int maxQuantity = GlobalVars.db.getQuantity(itemID);
									
									if(maxQuantity < quantity){
										errorString.append("Your cannot buy more items than the seller is selling. <br />");
									}
								}
							}
							else{
								errorString.append("You must buy a positive number of the item. <br />");
							}
						}
						catch(Exception e){
							errorString.append("The quantity you entered is not a number. <br />");
						}
					}
					else{
						errorString.append("You must enter a value in the quantity box. <br />");
					}
				}
				else{
					errorString.append("You cannot bid for an item without choosing the quantity. <br />");
				}
				
				// If there are no errors we can enter the users bid
				if(errorString.toString().equals("")){
					// Check the userID and authToken are correct
					if(GlobalVars.db.checkAuthToken(userID, authToken)){
						// Insert the bid in to the DB
						GlobalVars.db.insertBid(userID, itemID, quantity, bid, maxBid);
						
						// forward to you have bid!
						response.sendRedirect("./confirmbid?userID="+userID+"&authToken="+authToken);
						
					}
					else
						errorString.append("Your userID and authToken don't match. (userID: "+ userID + ", authToken: " + authToken + "<br />");
				}
			}
			
			// If we have made it down to here then something is wrong
			makePage(request, response, errorString.toString());
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		makePage(request, response, "");
	}
	
	public void makePage(HttpServletRequest request, HttpServletResponse response, String errorString)  throws ServletException, IOException {
		// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
		PrintWriter out = response.getWriter();
		out.println(errorString);
		
		
		// Do HTML4 or 5 depending on the global variables
		if(GlobalVars.isHTML4)
			createHTML4(request, response, out);
		else
			createHTML5(request, response, out);
	}
	
	public HttpServletResponse createHTML4(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
		Map<String, String[]> paramMap = request.getParameterMap();
		
		// Set the return type
		response.setContentType("text/html");
		
		
		//java.util.Date dt = new java.util.Date();
		//SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//String currentTime = sdf.format(dt);
		
		//TODO: we could be looking at an old item, we need to check the table for finished bids
		// set old item to be true if that's the case
		// Get the item we are going to display
		
		Item currentItem = null;
		
		// Get the itemID
		if(paramMap.containsKey("itemID")){
			if(!request.getParameter("itemID").equals(EMPTY)){
				// Make sure the itemID is a number
				try{
					int itemID = Integer.parseInt(request.getParameter("itemID"));
					
					currentItem = GlobalVars.db.getItem(itemID, Boolean.TRUE);
				}
				catch(Exception e){ }
			}
		}
		
		// Get the userID and auth token
		String userID=null;
		String authToken=null;
		if(paramMap.containsKey("userID")){
			userID = request.getParameter("userID");
		}
		
		if(paramMap.containsKey("authToken")){
			authToken = request.getParameter("authToken");
		}
		
		// Include header
		out.println("<HTML>");
		out.println("<HEAD><TITLE>View Item</TITLE></HEAD>");
		out.println("<BODY>");
		
		if(currentItem == null){
			out.println("<div id=\"floatcenter\"> Sorry, the item ID you entered is invalid </div>");
		}
		else{
			// Get the items images
			currentItem.setImages(GlobalVars.db.getItemImages(currentItem.getID()));
			
			// See if the auction is still ongoing
			boolean oldItem = false;
			Date now = new Date();
			if(currentItem.getEndDate().before(now)){
				oldItem = true;
			}
			
			// Put the first image at the top right
			out.println("<div id=\"floatright\">");
			out.println("<div id=\"image\">");
			if(currentItem.getImages().isEmpty())
				out.println("<img width=\"150\" height=\"150\" src=\"blank.jpg\" alt=\"Sorry. No image provided\">");	
			else
				out.println("<img width=\"150\" height=\"150\" src=\"" + currentItem.getImages().get(0).getUrl() + "\" alt=\"" + currentItem.getImages().get(0).getDescription() + "\">");		
			out.println("</div>");
			out.println("</div>");
			
			// Add item name and bid options to the right
			out.println("<div id=\"floatcenter\">");
			out.println(currentItem.getName() + "<br />");
			out.println("Item condition: <br />");
			out.println("Bidding Ends: " + currentItem.getEndDate() + "<br />");
			out.println("Bidding History: " + currentItem.getNoOfBids() + "<br />");
			
			// If the auction is still going then the user can bid
			if(!oldItem){
				out.println("Current Price: " + currentItem.getCurrentBid() + "<br />");
				
				// Say if the reserve is met or not
				if(currentItem.getCurrentBid()<currentItem.getReservePrice())
					out.println("The reserve price has NOT yet been met<br />");
				else
					out.println("The reserve price HAS been met<br />");
				
				out.println("<form name=\"bid\" action=\"viewitem\" method=\"POST\">");
				
				// If there is a userID or authToken then make sure they get passed to the next page
				if(userID != null)
					out.println("<input type=\"hidden\" name=\"userID\" value=\""+userID+"\">");
				if(authToken != null)
					out.println("<input type=\"hidden\" name=\"authToken\" value=\""+authToken+"\">");
				
				out.println("<input type=\"hidden\" name=\"itemID\" value=\""+currentItem.getID()+"\">");
				out.println("Quantity: <input type=\"text\" name=\"quantity\" size=\"2\" maxlength=\"2\" value=\"" + (paramMap.containsKey("quantity") ?  request.getParameter("quantity") : "")+ "\"> (" + currentItem.getQuantity() + " available) <br />");
				out.println("Your Bid: <input type=\"text\" name=\"bid\" size=\"10\" maxlength=\"10\" value=\"" + (paramMap.containsKey("bid") ?  request.getParameter("bid") : "")+ "\"> (Enter more than $" + currentItem.getCurrentBid() + ") <br />");
				out.println("Your Maximum Bid: <input type=\"text\" name=\"maxBid\" size=\"10\" maxlength=\"10\" value=\"" + (paramMap.containsKey("maxBid") ?  request.getParameter("maxBid") : "")+ "\"> (Enter more than $" + currentItem.getCurrentBid() + ") <br />");
				out.println("<input type=\"submit\" value=\"Bid\">");
				out.println("</form><br />");
			
				// Add the 'buy now' option if it is available
				if(currentItem.getBuyNowPrice()>currentItem.getReservePrice()){
					out.println("<form name=\"buyNow\" action=\"buyitem\" method=\"POST\">");
					
					// If there is a userID or authToken then make sure they get passed to the next page
					if(userID != null)
						out.println("<input type=\"hidden\" name=\"userID\" value=\""+userID+"\">");
					if(authToken != null)
						out.println("<input type=\"hidden\" name=\"authToken\" value=\""+authToken+"\">");
					
					out.println("<input type=\"hidden\" name=\"itemID\" value=\""+currentItem.getID()+"\">");
					out.println(currentItem.getBuyNowPrice() + " <input type=\"submit\" value=\"Buy Now\">");
					out.println("</form>");
				}
			}
			// If the item has finished, just display the final price
			else{
				out.println("Bidding on this item has finished<br />");
				out.println("Sale Price: " + currentItem.getMaxBid() + "<br />");
			}
			
			out.println("</div> <br />");
			
			// Add the larger description field
			out.println("<div id=\"floatcenter\">");
			out.println("Description<br />");
			out.println(currentItem.getDescription());
			out.println("</div> <br />");
			
			// Add all of the items pictures
			if(!currentItem.getImages().isEmpty()){
				out.println("<div id=\"floatcenter\">");
				out.println("Images<br />");
				
				for(Image currentImg:currentItem.getImages()){
					out.println("<img width=\"150\" height=\"150\" src=\"" + currentImg.getUrl() + "\" alt=\"" + currentImg.getDescription() + "\">");		
				}
				
				out.println("</div> <br />");
			}
			
			//TODO: add the questions and answers
			
		}
		
		// Include footer
		out.println("</BODY></HTML>");
		
		return response;
	}
	
	public HttpServletResponse createHTML5(HttpServletRequest request, HttpServletResponse response, PrintWriter out){
		
		
		return response;
	}
	
}
